package com.len.core.filter;

import com.len.base.CurrentUser;
import com.len.entity.SysUser;
import com.len.service.MenuService;
import com.len.service.SpOrderService;
import com.len.service.SysUserService;
import java.io.IOException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.len.util.JsonUtil;
import com.len.util.Md5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import static cn.hutool.core.util.StrUtil.uuid;

/**
 * @author zhuxiaomeng
 * @date 2017/12/11.
 * @email 154040976@qq.com
 * 拦截器 校验用户是否已授权 未授权返回到登录界面
 */
@Slf4j
public class PermissionFilter extends AuthorizationFilter {

  @Autowired
  private SysUserService userService;
  @Autowired
  private SpOrderService spOrderService;
  @Autowired
  private MenuService menuService;

  @Override
  protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse,
      Object o) throws Exception {
    String[] roles=(String[])o;

    Subject sub = getSubject(servletRequest, servletResponse);
    Session session= sub.getSession();
    String userName = servletRequest.getParameter("username");
    String invite = servletRequest.getParameter("invite");
    String pass = servletRequest.getParameter("password");
//    if (StringUtils.isBlank(userName)) {
//      return false;
//    }
//    if (StringUtils.isBlank(pass)) {
//      return false;
//    }
    CurrentUser user= (CurrentUser) session.getAttribute("currentPrincipal");
    if(StringUtils.isNotEmpty(userName)) {
       int num= spOrderService.userNum(userName);
       if(num==0){
      SysUser user1 = new SysUser();
      user1.setId(uuid());
      user1.setDelFlag(Byte.parseByte("0"));
      user1.setUsername(userName);
      String pwd = Md5Util.getMD5(pass.trim(), userName.trim());
      user1.setPassword(pwd);
//      user1.setPassword(pass);
      user1.setJSR(invite);
      userService.insert(user1);
       }
      return false;
    }
    return true;
  }

  @Override
  protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
      throws IOException {

      saveRequest(request);
      WebUtils.issueRedirect(request, response, "/goLogin");
    return false;
  }
}
